var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __read = (this && this.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __spread = (this && this.__spread) || function () {
    for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));
    return ar;
};
import React, { useMemo, useState, useEffect, useRef, useImperativeHandle } from "react";
import { View, ScrollView, Text, Block } from "@tarojs/components";
import { AtIcon } from "taro-ui";
import "./index.scss";
import { useVirtualList } from "./hook";
/**
 * 对象浅比较
 * @param {object} a
 * @param {object} b
 * @returns
 */
export function shallowEqual(a, b) {
    if (a === b)
        return true;
    if (a === undefined || b === undefined) {
        return false;
    }
    var keysA = Object.keys(a);
    var keysB = Object.keys(b);
    if (keysA.length !== keysB.length)
        return false;
    var hasDiff = keysA.some(function (key) { return a[key] !== b[key]; });
    return !hasDiff;
}
/**
 * virtual-flow-list 列表展示组件
 */
var FlowList = function (_a, ref) {
    var api = _a.api, apiData = _a.apiData, initData = _a.initData, scrollStyle = _a.scrollStyle, onScroll = _a.onScroll, onScrollClick = _a.onScrollClick, _b = _a.scrollY, scrollY = _b === void 0 ? true : _b, onScrollToUpper = _a.onScrollToUpper, onRefresherPulling = _a.onRefresherPulling, onRefresherRestore = _a.onRefresherRestore, onRefresherRefreshFun = _a.onRefresherRefreshFun, onFetchedData = _a.onFetchedData, renderItem = _a.renderItem, renderListHeaderComponent = _a.renderListHeaderComponent, renderListEmptyComponent = _a.renderListEmptyComponent, renderLoadingComponent = _a.renderLoadingComponent, refresherBackground = _a.refresherBackground, noMoreDataStyle = _a.noMoreDataStyle, _c = _a.isScrollToTop, isScrollToTop = _c === void 0 ? false : _c, _d = _a.hasPopData, hasPopData = _d === void 0 ? false : _d, contentClassName = _a.contentClassName, popDataFunc = _a.popDataFunc, scrollTop = _a.scrollTop, _e = _a.segmentNum, segmentNum = _e === void 0 ? 20 : _e, _f = _a.screenNum, screenNum = _f === void 0 ? 2 : _f, _g = _a.listId, listId = _g === void 0 ? "zt-virtial-list" : _g, scrollViewProps = _a.scrollViewProps;
    var _h = __read(useState(function () {
        return initData ? initData : [];
    }), 2), data = _h[0], setData = _h[1];
    var _j = __read(useState(false), 2), refreshing = _j[0], setRefreshing = _j[1];
    var _k = __read(useState(false), 2), noMoreData = _k[0], setNoMoreData = _k[1];
    var _l = __read(useState(false), 2), hasLoadData = _l[0], setHasLoadData = _l[1];
    var _m = __read(useState(apiData), 2), apiProps = _m[0], setApiProps = _m[1];
    var _o = __read(useState(""), 2), scrollIntoView = _o[0], setScrollIntoView = _o[1];
    var pageNo = useRef(1);
    var loading = useRef(false);
    var _p = __read(useVirtualList({
        data: data,
        screenNum: screenNum,
        listId: listId,
        scrollViewProps: scrollViewProps,
        segmentNum: segmentNum,
        pageNo: pageNo.current
    }), 1), twoList = _p[0];
    useEffect(function () {
        if (isScrollToTop) {
            setScrollIntoView("scrollDivTop");
        }
        else {
            setScrollIntoView("");
        }
    }, [isScrollToTop]);
    var handleScroll = function (e) {
        var top = e.detail.scrollTop;
        if (top < 30) {
            setScrollIntoView("");
        }
        onScroll && onScroll(e);
    };
    useImperativeHandle(ref, function () {
        return {
            refresh: function () {
                onRefresherRefresh();
            },
            getData: function () {
                return data;
            },
            setData: function (res) {
                setData(res);
            }
        };
    });
    useEffect(function () {
        fetchData(true);
    }, [apiProps]);
    useEffect(function () {
        if (!shallowEqual(apiData, apiProps)) {
            setApiProps(apiData);
        }
    }, [apiData, apiProps]);
    var fetchData = function (refresh) { return __awaiter(void 0, void 0, void 0, function () {
        var arr_1, res;
        return __generator(this, function (_a) {
            if (pageNo.current > 1) {
                if (loading.current)
                    return [2 /*return*/];
                loading.current = true;
            }
            if (refresh) {
                pageNo.current = 1;
            }
            // let params = {pageNo: pageNo.current, pageSize: 20, ...apiData};
            try {
                arr_1 = [];
                Array(20)
                    .fill(0)
                    .forEach(function (__item, index) {
                    arr_1.push(data.length + index);
                });
                res = {
                    entities: arr_1
                };
                if (!res) {
                    loading.current = false;
                    setRefreshing(false);
                    if (!refresh) {
                        setNoMoreData(true);
                    }
                    else {
                        setHasLoadData(true);
                    }
                }
                else {
                    res && afterFetchData(res);
                    loading.current = false;
                }
            }
            catch (res) {
                loading.current = false;
                setRefreshing(false);
                setHasLoadData(true);
                if (!refresh) {
                    setNoMoreData(true);
                }
            }
            return [2 /*return*/];
        });
    }); };
    var afterFetchData = function (res) {
        var resEntities = res && res.entities;
        var fetchData = resEntities && onFetchedData
            ? onFetchedData(res.entities || [], res)
            : null;
        var entities = fetchData || resEntities || [];
        var extData = [];
        if (pageNo.current === 1) {
            extData = __spread(entities);
            setNoMoreData(false);
        }
        else {
            extData = __spread(data, entities);
        }
        //  后台返回的数据有可能会少于pageSize但还有下一页数据
        if (entities.length < 20) {
            setNoMoreData(true);
        }
        else {
            pageNo.current++;
        }
        setData(extData);
        setHasLoadData(true);
        if (hasPopData) {
            popDataFunc && popDataFunc(extData);
        }
        setRefreshing(false);
    };
    var handleLoadMore = function () {
        if (loading.current || noMoreData) {
            return;
        }
        fetchData(false);
    };
    var onRefresherRefresh = function () {
        onRefresherRefreshFun && onRefresherRefreshFun();
        setRefreshing(true);
        fetchData(true);
    };
    var renderLoadingComponentDefault = function () {
        return (React.createElement(View, { className: "loading-wrap" },
            React.createElement(AtIcon, { className: "loading-icon", value: "loading-3", size: "32", color: "#aaa" }),
            React.createElement(Text, { className: "loading-text" }, "\u52A0\u8F7D\u4E2D\u2026")));
    };
    var renderListFooterComponent = function () {
        if (!hasLoadData) {
            return renderLoadingComponent
                ? renderLoadingComponent()
                : renderLoadingComponentDefault();
        }
        if (!data.length)
            return null;
        return (React.createElement(View, { className: "no-more", style: noMoreDataStyle }, noMoreData ? "没有更多了" : "内容加载中..."));
    };
    var renderRowItem = function () {
        if (twoList.length > 0) {
            return twoList === null || twoList === void 0 ? void 0 : twoList.map(function (item, pageIndex) {
                return (React.createElement(View, { key: pageIndex, className: "zt-wrap-item wrap_" + pageIndex }, (item === null || item === void 0 ? void 0 : item.length) > 0 ? (React.createElement(Block, null, item.map(function (el, index) {
                    return renderItem === null || renderItem === void 0 ? void 0 : renderItem(el, pageIndex * segmentNum + index, pageIndex);
                }))) : (React.createElement(View, { style: { height: (item === null || item === void 0 ? void 0 : item.height) + "px" } }))));
            });
        }
        else if (twoList.length == 0 && hasLoadData) {
            if (renderListEmptyComponent) {
                return renderListEmptyComponent();
            }
            else {
                return null;
            }
        }
        else {
            return null;
        }
    };
    var renderHeader = useMemo(function () {
        return renderListHeaderComponent && renderListHeaderComponent();
    }, [renderListHeaderComponent]);
    return (React.createElement(View, { className: "flow-list-wrap" },
        React.createElement(ScrollView, __assign({ className: "scrollview", id: listId, scrollWithAnimation: true, style: scrollStyle, scrollY: scrollY, refresherEnabled: true, refresherTriggered: refreshing, refresherBackground: refresherBackground, onRefresherRefresh: onRefresherRefresh, scrollIntoView: scrollIntoView, scrollTop: scrollTop, onRefresherPulling: onRefresherPulling, onRefresherRestore: onRefresherRestore, onScrollToUpper: onScrollToUpper, lowerThreshold: 200, onScroll: handleScroll, onScrollToLower: handleLoadMore, onClick: function (e) { return onScrollClick && onScrollClick(e); } }, scrollViewProps),
            React.createElement(View, { id: "scrollDivTop" }),
            renderHeader,
            React.createElement(View, { className: "list-guest list-guest-common " + contentClassName }, renderRowItem()),
            renderListFooterComponent())));
};
export default React.forwardRef(FlowList);
